import { Chat, Select } from "@kousum/semi-ui-vue";
import { defineComponent, ref, onMounted } from "vue";
import { getChatInfo, getDSVersionList } from "../api/getInfo";
import "./Chat.css";
const defaultMessage = [
  {
    role: "assistant",
    id: "1",
    createAt: 1715676751919,
    content: "您好，有什么我能帮您的吗？",
  },
];

const roleInfo = {
  user: {
    name: "User",
    avatar:
      "https://lf3-static.bytednsdoc.com/obj/eden-cn/ptlz_zlp/ljhwZthlaukjlkulzlp/docs-icon.png",
  },
  assistant: {
    name: "Assistant",
    avatar:
      "https://lf3-static.bytednsdoc.com/obj/eden-cn/ptlz_zlp/ljhwZthlaukjlkulzlp/other/logo.png",
  },
  system: {
    name: "System",
    avatar:
      "https://lf3-static.bytednsdoc.com/obj/eden-cn/ptlz_zlp/ljhwZthlaukjlkulzlp/other/logo.png",
  },
};

const uploadProps = { action: "http://123.153.1.18:8093/api/generate" };
const uploadTipProps = { content: "自定义上传按钮提示信息" };
// 通用样式
const commonOuterStyle = {
  border: "gray",
  backgroundColor: "#fff",
  borderRadius: "16px",
  width: "100vw",
  height: "80vh",
};

// 选择框
const selectContainer = {
  position: "absolute",
  top: "20px",
  left: "550px",
  zIndex: "999",
};
// 深度拷贝
let id = 0;
// 创建一个新的助手消息
const createNewAssistantMessage = () => ({
  role: "assistant",
  id: getId(),
  createAt: Date.now(),
  content: "", // 初始内容为空
});
// 创建一个新的助手消息
let newAssistantMessage = ref(createNewAssistantMessage());
//获取id
function getId() {
  return `id-${id++}`;
}

const AIChat = defineComponent(() => {
  const message = ref(defaultMessage);
  const mode = ref("bubble");
  const align = ref("leftRight");
  const list = ref([]);
  const curDSVersion = ref("deepseek-r1:1.5b");
  const onMessageSend = (content, attachment) => {
    console.log(attachment, "attachment");

    const requestData = {
      model: curDSVersion.value,
      prompt: content,
      stream: true,
    };
    // 创建一个新的助手消息对象
    newAssistantMessage.value = createNewAssistantMessage();
    message.value = [...message.value, newAssistantMessage.value];
    getChatInfo(JSON.stringify(requestData)).then(async (stream) => {
      try {
        // 创建解码器和读取器
        const reader = stream.getReader();
        const decoder = new TextDecoder();
        let partialContent = "";
        // 逐步读取流式数据
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          // 解码接收到的数据
          const chunk = decoder.decode(value, { stream: true });
          partialContent += chunk;
          // 按行解析数据块
          const lines = chunk.split("\n");
          for (const line of lines) {
            try {
              let token = JSON.parse(line).response;
              // // 更新助手消息的内容
              newAssistantMessage.value.content += token;
              // // 触发 Vue 的响应式更新
              message.value = [...message.value];
              newAssistantMessage.value.scrollToBottom({ animation: true });
            } catch (error) {
              console.warn("无法解析数据块:", line);
            }
          }
        }
      } catch (error) {
        console.error("处理流式数据时出错:", error);
      }
    });
  };

  const onChatsChange = (chats) => {
    message.value = chats;
  };

  const onMessageReset = (e) => {
    console.log(e);

    setTimeout(() => {
      const lastMessage = message.value[message.value.length - 1];
      const newLastMessage = {
        ...lastMessage,
        status: "complete",
        content: "This is a mock reset message.",
      };
      message.value = [...message.value.slice(0, -1), newLastMessage];
    }, 200);
  };

  //版本选择
  const changeDSVersion = (val) => {
    console.log(val, "val");
    curDSVersion.value = val;
  };

  onMounted(() => {
    getDSVersionList().then((res) => {
      if (res.models.length > 0) {
        res.models.map((item, index) => {
          list.value.push({
            value: item.model,
            label: item.name,
            otherKey: index,
          });
        });
        console.log(list.value, "12312312");
      }
    });
  });

  return () => (
    <>
      <div style={selectContainer}>
        <Select
          placeholder="请选择DeepSeek版本"
          onChange={changeDSVersion}
          defaultValue={curDSVersion.value}
        >
          {list.value.map((item) => {
            return (
              <Select.Option value={item.value}>{item.label}</Select.Option>
            );
          })}
        </Select>
      </div>
      <div class="chat-container">
        <Chat
          key={align.value + mode.value}
          align={align.value}
          mode={mode.value}
          uploadProps={uploadProps}
          style={commonOuterStyle}
          chats={message.value}
          roleConfig={roleInfo}
          onChatsChange={onChatsChange}
          onMessageSend={onMessageSend}
          onMessageReset={onMessageReset}
          uploadTipProps={uploadTipProps}
        />
      </div>
    </>
  );
});

export default AIChat;
